﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace GetSize
{
    public class Entry
    {
        public bool IsDirectory { get; set; }
        public string FullName { get; set; }

        public long FileSize { set; get; }
        private int ChildrenCount;

        public List<Entry> Children { get; set; }

        public Entry()
        {
            Children = new List<Entry>();
        }
        public Entry(string path) : this()
        {
            FullName = path;
        }

        public int GetChildrenCount()
        {
            if (!IsDirectory)
            {
                return 0;
            }

            if (ChildrenCount != 0)
            {
                return ChildrenCount;
            }
            try
            {
                ChildrenCount = Children.Count + Children.Sum(entry => entry.Children.Count);
            }
            catch (Exception)
            {
                ChildrenCount = -1;
            }
            return ChildrenCount;
        }

        public void GetFileSize()
        {
            if (IsDirectory)
            {
                return;
            }
            if (FileSize > 0)
            {
                return;
            }
            try
            {
                FileSize = new FileInfo(FullName).Length;
            }
            catch (FileNotFoundException)
            {
                IsDirectory = true;
            }
            catch (UnauthorizedAccessException)
            {
                FileSize = -1;
            }
        }

        public long GetSize()
        {
            if (IsDirectory)
            {
                return Children.Sum(entry => entry.GetSize());
            }

            return FileSize;
        }

        public override string ToString()
        {
            return $"{Path.GetFileName(FullName)}, {(IsDirectory ? "Directory" : "File")}";
        }
    }
}
